package com.taomu.app.zongchouhuli.moudle.mine.contract.impl;

import android.text.TextUtils;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jakewharton.rxbinding2.widget.TextViewAfterTextChangeEvent;
import com.taomu.app.zongchouhuli.R;
import com.taomu.app.zongchouhuli.entity.BaseChangeResponse;
import com.taomu.app.zongchouhuli.entity.BaseResponse;
import com.taomu.app.zongchouhuli.http.api.HttpObserver;
import com.taomu.app.zongchouhuli.http.api.Request;
import com.taomu.app.zongchouhuli.http.res.ResBankEntity;
import com.taomu.app.zongchouhuli.http.res.ResUserInfoEntity;
import com.taomu.app.zongchouhuli.moudle.mine.contract.UserBindBankContract;
import com.taomu.app.zongchouhuli.utils.ParseUtil;
import com.taomu.app.zongchouhuli.utils.StorageHelper;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Function4;
import io.reactivex.functions.Function5;
import io.reactivex.schedulers.Schedulers;

public class UserBindBankPresenter implements UserBindBankContract.Presenter {

    private UserBindBankContract.View mContractView;

    private CompositeDisposable disposable;

    public UserBindBankPresenter(UserBindBankContract.View mConatractView){
        this.mContractView = mConatractView;
        this.disposable = new CompositeDisposable();
    }

    @Override
    public void isSmsCanClick(TextView tv1) {
        isEditTextInputTextObservable(tv1).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if(mContractView != null){
                            if(aBoolean){
                                mContractView.setSmsCanClick(R.color.base_blue,true);
                            }else{
                                mContractView.setSmsCanClick(R.color.text_normal_gary,false);
                            }

                        }
                    }
                });
    }

    @Override
    public void isNextCanClick(TextView tv1, TextView tv2, TextView tv3, TextView tv4, TextView tv5) {
        Observable.combineLatest(isEditTextInputTextObservable(tv1),
                isEditTextInputTextObservable(tv2),
                isEditTextInputTextObservable(tv3),
                isEditTextInputTextObservable(tv4),
                isEditTextInputTextObservable(tv5),
                new Function5<Boolean, Boolean, Boolean, Boolean, Boolean, Boolean>() {
                    @Override
                    public Boolean apply(Boolean aBoolean, Boolean aBoolean2, Boolean aBoolean3, Boolean aBoolean4, Boolean aBoolean5) throws Exception {
                        return aBoolean&&aBoolean2&&aBoolean3&&aBoolean4&&aBoolean5;
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if(mContractView != null){
                            if(aBoolean){
                                mContractView.setNextCanClick(R.drawable.shape_next_blue,true);
                            }else{
                                mContractView.setNextCanClick(R.drawable.shape_next_gray,false);
                            }

                        }
                    }
                });
    }

    @Override
    public void detch() {
        if(timeDisposable != null){
            timeDisposable.dispose();
            timeDisposable = null;
        }
    }

    private Long time = 60l;

    private Disposable timeDisposable;

    @Override
    public void getSmsCode(String phone) {
        Request.getIntence().getSmsCode(phone)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<String>(mContractView,disposable,true) {
                    @Override
                    public void onNext(String baseResponse) {
                        if(mContractView != null){
                            mContractView.setSendSmsSuccess(baseResponse);
                        }
                        countDown();
                    }
                });
    }

    private void countDown(){
        Observable.interval(1,TimeUnit.SECONDS)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        return time - aLong;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        timeDisposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        if(aLong<0){
                            if(timeDisposable != null){
                                timeDisposable.dispose();
                                timeDisposable = null;
                            }
                            mContractView.setBackTime("获取验证码(60)s",true);
                        }else{
                            mContractView.setBackTime("获取验证码("+String.valueOf(aLong)+"s)",false);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void getBankInfo(int _id) {
        Request.getIntence().getBankInfo(StorageHelper.getToken(),String.valueOf(_id))
                .flatMap(new Function<String, Observable<BaseChangeResponse<ResBankEntity>>>() {
                    @Override
                    public  Observable<BaseChangeResponse<ResBankEntity>> apply(String json) throws Exception {
                        BaseResponse<JSONObject> baseResponse = ParseUtil.parseObject(json,BaseResponse.class);
                        BaseChangeResponse<ResBankEntity> data = new BaseChangeResponse<>();
                        data.setData(ParseUtil.parseObject(baseResponse.getData().toString(),ResBankEntity.class));
                        data.setCount(baseResponse.getCount());
                        return Observable.just(data);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseChangeResponse<ResBankEntity>>(mContractView,disposable,true) {
                    @Override
                    public void onNext(BaseChangeResponse<ResBankEntity> data) {
                        if(mContractView != null){
                            mContractView.setBankInfo(data.getData());
                        }
                    }
                });
    }

    @Override
    public void submit(String card_username, String card_phone, String card_num, String phone, String code) {
        Request.getIntence().addBank(StorageHelper.getToken(),card_username,card_phone,card_num,phone,code)
                .flatMap(new Function<String, Observable<BaseChangeResponse<ResBankEntity>>>() {
                    @Override
                    public  Observable<BaseChangeResponse<ResBankEntity>> apply(String json) throws Exception {
                        BaseResponse<JSONObject> baseResponse = ParseUtil.parseObject(json,BaseResponse.class);
                        BaseChangeResponse<ResBankEntity> data = new BaseChangeResponse<>();
                        data.setData(ParseUtil.parseObject(baseResponse.getData().toString(),ResBankEntity.class));
                        data.setCount(baseResponse.getCount());
                        return Observable.just(data);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseChangeResponse<ResBankEntity>>(mContractView,disposable,true) {
                    @Override
                    public void onNext(BaseChangeResponse<ResBankEntity> baseResponse) {
                        if(mContractView != null){
                            mContractView.setSubmitResults();
                        }
                    }
                });
    }

    @Override
    public void changedbank(int id, String card_username, String card_phone, String card_num, String phone, String code) {
        Request.getIntence().changedBank(StorageHelper.getToken(),String.valueOf(id),card_username,card_phone,card_num,phone,code)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<String>(mContractView,disposable,true) {
                    @Override
                    public void onNext(String s) {
                        if(mContractView != null){
                            mContractView.setChangedResults();
                        }
                    }
                });

    }

    private Observable<Boolean> isEditTextInputTextObservable(TextView tv) {
        return RxTextView.afterTextChangeEvents(tv)
                .map(new Function<TextViewAfterTextChangeEvent, Boolean>() {
                    @Override
                    public Boolean apply(TextViewAfterTextChangeEvent event) throws Exception {
                        return !TextUtils.isEmpty(event.view().getText());
                    }
                });
    }

    @Override
    public void onStart() {

    }

    @Override
    public void onDetch() {
        mContractView = null;
        if(disposable != null){
            disposable.dispose();
            disposable = null;
        }
    }
}
